package com.monster.starter.core.common.entity;

import com.monster.starter.core.utils.IoUtils;
import com.monster.utils.StringUtils;
import jakarta.servlet.ServletInputStream;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletRequestWrapper;
import lombok.Getter;

import java.io.IOException;
import java.nio.charset.StandardCharsets;

/**
 * 重写request请求
 *
 * @author kuang
 */
public class MonsterHttpServletRequest extends HttpServletRequestWrapper {
    /**
     * 请求的路径
     */
    @Getter
    private String path;
    /**
     * 请求的参数
     */
    @Getter
    private String body;
    /**
     * 模式
     */
    @Getter
    private boolean routeMode;
    /**
     * 路由
     */
    @Getter
    private String route;
    /**
     * 全路径
     */
    @Getter
    private String pathURI;

    /**
     * Constructs a request object wrapping the given request.
     *
     * @param request The request to wrap
     * @throws IllegalArgumentException if the request is null
     */
    public MonsterHttpServletRequest(HttpServletRequest request, Boolean routeMode) {
        super(request);
        this.routeMode = routeMode;
        if (routeMode) {
            // 开启二级域名模式，将请求路径里面的第一个/和第二个/里面的内容提取出来
            String path = super.getServletPath();
            this.path = path.substring(StringUtils.ordinalIndexOf(path, "/", 2));
            route = path.substring(1, StringUtils.ordinalIndexOf(path, "/", 2));
            pathURI = super.getContextPath() + this.path;
        } else {
            this.path = super.getServletPath();
            this.pathURI = super.getRequestURI();
        }
    }

    @Override
    public String getRequestURI() {
        return pathURI;
    }

    @Override
    public StringBuffer getRequestURL() {
        return super.getRequestURL();
    }

    @Override
    public String getServletPath() {
        return path;
    }

    public String getSubdomainName() {
        return route;
    }

    /**
     * 返回请求流中的字符串
     *
     * @return 请求流中的字符串
     */
    public String getBody() throws IOException {
        if (body == null) {
            body = IoUtils.toString(super.getInputStream(), StandardCharsets.UTF_8);
        }
        return body;
    }

    @Override
    public ServletInputStream getInputStream() throws IOException {
        return IoUtils.createServletInputStream(getBody());
    }
}
